package com.example.myblog.controller;


import com.example.myblog.dto.BlogDTO;
import com.example.myblog.dto.BlogMapDTO;
import com.example.myblog.dto.BlogMessageDTO;
import com.example.myblog.dto.BlogSearchDTO;
import com.example.myblog.entity.Blog;
import com.example.myblog.exception.BaseException;
import com.example.myblog.result.ResponseBean;
import com.example.myblog.service.BlogService;
import com.example.myblog.vo.BlogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 博客 前端控制器
 * </p>
 *
 * @author 叶兴
 * @since 2022-09-29
 */
@RestController
@RequestMapping("/blog")
public class BlogController {

    BlogService blogService;

    @Autowired
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    /**
     * 新增一篇博客
     * @param blogDTO
     * @return ResponseBean
     */
    @PostMapping("/blogs")
    public ResponseBean addBlog(
            @RequestBody BlogVO blogVO) {
        blogService.insertBlog(blogVO);
        return ResponseBean.success();
    }

    /**
     * 删除博客
     * @param id
     * @return
     * @throws BaseException
     */
    @DeleteMapping("/delete/{id}")
    public ResponseBean deleteBlog(
            @PathVariable String id
    ) throws BaseException {
        blogService.deleteBlog(id);
        return ResponseBean.success();
    }

    /**
     * 根据博客id获取当前博客内容
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseBean getMyBlogs(
            @PathVariable String id
    ) {
        BlogMessageDTO blog = blogService.getOneBlog(id);
        return ResponseBean.success(blog);
    }

    /**
     * 返回归档
     * @return
     */
    @GetMapping("/archives")
    public ResponseBean getBlogArchives() {
        Map<String, List<BlogMapDTO>> mapDTOS = blogService.getBlogArchives();
        return ResponseBean.success(mapDTOS);
    }

    /**
     * 返回博客记录数
     * @return
     */
    @GetMapping("/count")
    public ResponseBean getCount() {
        int count = blogService.blogCount();
        return ResponseBean.success(count);
    }

    /**
     * 根据前端输入的数据进行搜索
     * @param query
     * @return
     */
    @GetMapping("/searchBlog")
    public ResponseBean getBlog(@RequestParam("query")String query) {
        List<BlogSearchDTO> blogSearchDTOS = blogService.searchBlog(query);
        return ResponseBean.success(blogSearchDTOS);
    }
}
